package com.zhangfei.service;

import com.zhangfei.config.SerialTagEnum;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class IdService {

    /**
     * 单号位数，自行扩展
     */
    private static final int WIDTH_5 = 5;


    @Resource
    private RedissonClient redissonClient;



    /**
     * 依赖redis的单号生成规则
     *
     * @param serialTag 单据类型唯一标识
     * @return 拼接Tag + yyyyMMdd + id
     */
    public String getSerialNo(SerialTagEnum serialTag) {
        String date = getThisDate(new Date());
        Long id = getSerialId(serialTag, date);
        return serialTag.name() + date + String.format("%0" + WIDTH_5 + "d", id);
    }


    private Long getSerialId(SerialTagEnum serialTag, String dateStr) {
        String key = serialTag.getValue().concat(dateStr);
        // 通过redis的自增获取序号
        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
        // 设置到期时间1天
        atomicLong.expire(1, TimeUnit.DAYS);
        return atomicLong.incrementAndGet();
    }


    public static String getThisDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return formatter.format(localDateTime);
    }


}
